const express = require('express')
const router = express.Router()
const multer = require('multer')
const upload = multer()
const oss = require('ali-oss')
const{generate19DigitId}=require('../../../utils/idUtils')

router.post('/file/upload', upload.single('file'), async (req, res) => {
    try {
        console.log('上传的文件信息:', req.file)

        //使用阿里云oss直传保存图片
        // 创建 OSS 客户端实例
        const client = new oss({
            region: 'oss-cn-guangzhou', // OSS 区域
            endpoint: 'oss-cn-guangzhou.aliyuncs.com', // OSS 端点
            accessKeyId: 'LTAI5tNgCigViMp2BpSFyria', // 访问密钥 ID
            accessKeySecret: 'mEb0JU0NpiAcsYKddZ8QDRoI2qQ9Tu', // 访问密钥
            bucket: 'tuitui-p4'
        })

        // 生成唯一文件名：目录/时间戳_原文件名
        const fileName = `el-exam/upload/file/${new Date().getFullYear()}/${new Date().getMonth() + 1}/${new Date().getDate()}/${generate19DigitId()}`
        const result = await client.put(fileName, req.file.buffer)

        console.log('上传成功:', result)
        return res.json({
            "msg": "操作成功！",
            "code": 0,
            "data": {
                "url": `${result.url}`
            },
            "success": true
        })
    } catch (error) {
        console.error(error);
        return res.status(500).json({ message: 'Internal server error' });
    }
})

module.exports = router